package cx.ath.skyflyer.chart;

import javax.microedition.lcdui.Font;
import javax.microedition.lcdui.Graphics;

/**
 *
 * @author Ahti Legonkov
 */
public class HorizontalAxis {

    public HorizontalAxis(Rectangle screenRect) {
        this.screen = screenRect;
    }

    /// Set the unit that the axis represents.
    public void setUnit(String unit) {
        this.unit = unit;
    }

    /// Set number of ticks to draw per axis.
    public void setTicks(int n) {
        ticks = n;
    }

    public void setMargins(Margins m) {
        this.margins = m;
    }

    /// Set minimum value of the axis.
    public void setMin(double min) {
        this.min = min;
    }

    /// Set maximum value os the axis.
    public void setMax(double max) {
        this.max = max;
    }

    /// Moves the view port to the left by one unit.
    public void moveLeft() {

    }

    /// Moves view port to the right by one unit.
    public void moveRight() {

    }

    /// Zooms in
    public void zoomIn() {

    }

    /// zooms out.
    public void zoomOut() {

    }

    /// Draw the axis on graphics context g.
    public void draw(Graphics g) {
        
        final int y = screen.height() - margins.bottom;

        final int arrowSize = 6;

        g.setColor(0);
        g.setStrokeStyle(Graphics.SOLID);

        // draw the axis unit label
        g.setFont(Font.getFont(Font.FACE_PROPORTIONAL, Font.STYLE_PLAIN, Font.SIZE_SMALL));
        g.drawString(unit, screen.width()-arrowSize, y-arrowSize/2, Graphics.BOTTOM | Graphics.HCENTER);

        // the axis
        g.drawLine(screen.left, y, screen.right, y);

        // arrow head
        g.drawLine(screen.right-arrowSize, y-arrowSize/2, screen.right, y);
        g.drawLine(screen.right-arrowSize, y+arrowSize/2, screen.right, y);

        // the ticks
        int pixelStep = (screen.width() - margins.left - margins.right)/ ticks;
        int valueStep = (int)(10.0 * (max - min) / (double)ticks);

        // the tick labels
        int value = (int)(min*10.0);
        int prevWidth = -1;
        for (int i = screen.left+margins.left; i < screen.right-arrowSize; i += pixelStep, value += valueStep) {
            g.drawLine(i, y, i, y-3);

            String strValue = "" + (value/10) + "." + (value%10);
            int strWidth = g.getFont().stringWidth(strValue);
            if (prevWidth < 0 || prevWidth/2 + strWidth/2 + 3 < pixelStep) {
                g.drawString(strValue, i, y, Graphics.TOP | Graphics.HCENTER);
                prevWidth = strWidth;
            }
            else {
                prevWidth = 0;
            }
        }
    }

    private String unit = "s";
    private double min = 0;
    private double max = 100;
    private double zoom = 1.0;
    private int pos = 50;
    private int ticks = 2;

    private Rectangle screen;
    private Margins margins = new Margins();
}
